package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.example.demo.domain.User;
import com.example.demo.persistence.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.JWTUtil;
import com.example.demo.utils.MD5Utils;
import com.example.demo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

@RestController
@RequestMapping("/userd")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userDao;

    /**
     * 用户注册
     */
    @GetMapping("/register")
    public Result registUser(String username,String password){

        boolean flag = false;
        User user = new User();
        String salt = UUID.randomUUID().toString().substring(0,32);
        user.setSalt(salt);
        user.setUsername(username);
        user.setPassword(MD5Utils.md5Encryption(password,salt));
        user.setRoles("admin");
        user.setPermission("user:add");
        //mybatis-plus操作数据库
        int insert = userDao.insert(user);
        if (insert > 0) {
            flag = true;
        }
        if (flag) {
            return Result.succ("注册成功");
        }
        return Result.fail("注册失败");
    }

    @GetMapping("/userLogind")
    public Result userLogin(@RequestParam String username, @RequestParam String password) throws UnsupportedEncodingException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userService.getOne(wrapper);
        Assert.notNull(user,"用户不存在~");
        String pwd = MD5Utils.md5Encryption(password, user.getSalt());
        if (!pwd.equals(user.getPassword())){
            throw new RuntimeException("密码错误~");
        }
        String token = JWTUtil.createToken(user);
        return Result.succ(200,"登陆成功",token);
    }


}
